﻿using System;
using System.Collections.Generic;
using System.Linq;
using NHibernate.Linq;
using ServiceStack.Logging;
using g42.Dto;
using g42.Entities;
using g42.MapEntitiesDto;

namespace g42.Repos
{
  public class StrasseRepository
  {
    ILog log;

    public StrasseRepository()
    {
      log = LogManager.GetLogger(GetType());
    }

    public Strasse Get()
    {
      try
      {
        using (var session = db.sessionFactory.OpenSession())
        {
          using (session.BeginTransaction())
          {
            // Entity-Objekt lesen
            var aStrasseList =
              (from md in session.Query<StrasseEnt>()
               select md);
            // Einfach den ersten nehmen
            var aStrasse = aStrasseList.First();
            // Entity-Objekt in DTO transformieren
            return aStrasse.ToStrasse();
          }
        }
      }
      catch (Exception E)
      {
        log.Error("Error StrasseRepository.Get(): " + E.Message + System.Environment.NewLine + E.InnerException);
        return null;
      }
    }

    public Strasse Store(Strasse dto)
    {
      try
      {
        using (var session = db.sessionFactory.OpenSession())
        {
          using (var transaction = session.BeginTransaction())
          {
            StrasseEnt ent = dto.ToStrasseEnt();
            session.SaveOrUpdate(ent); // die Id kommt beim Speichern zurück
            transaction.Commit();
            dto.Id = ent.Id;
            return dto;
          }
        }
      }
      catch (Exception E)
      {
        log.Error("Error StrasseRepository.Store(): " + E.Message + System.Environment.NewLine + E.InnerException);
        return null;
      }

    }

  }
}

